package Util::Taobao::Authenticate;
use Moose;
use namespace::autoclean;
use JSON;
use WWW::Curl::Easy;
use HTTP::Response;
use Digest::MD5 qw(md5_hex);
use URI::Escape;

sub get_userinfo {
	my ($self, $code, $appKey, $clientSecret, $gatewayUrl, $redirectUri, $oauthUri, $apiVersion) = @_;
	my %sysParams;
	$sysParams{"app_key"} = $appKey;
	$sysParams{"v"} = $apiVersion;
	$sysParams{"format"} = "json";
	$sysParams{"sign_method"} = "md5";
	$sysParams{"method"} = "taobao.user.seller.get";
	my $time = `date +"%Y-%m-%d %H:%M:%S"`;
	chomp($time);
	$sysParams{"timestamp"} = $time;
	$sysParams{"fields"} = "nick";

	my $post_fields = "code=$code&grant_type=authorization_code&client_id=$appKey&client_secret=$clientSecret&redirect_uri=$redirectUri";

	my $curl = WWW::Curl::Easy->new;
	$curl->setopt(CURLOPT_HEADER,1);
	$curl->setopt(CURLOPT_POSTFIELDS, $post_fields);
	$curl->setopt(CURLOPT_URL, $oauthUri);

	my $response;
	$curl->setopt(CURLOPT_WRITEDATA,\$response);

	my $retcode = $curl->perform;

	my %resData;
	if ($retcode == 0) {
		$response = HTTP::Response->parse($response);
		my $xml = $response->decoded_content;
		my $json = from_json($xml);
		$resData{'code'} = 0;
		$resData{"nick"} = $json->{'taobao_user_nick'};
		$resData{"userid"} = $json->{'taobao_user_id'};
		$resData{"session"} = $json->{'access_token'};
		$resData{"refresh_token"} = $json->{'refresh_token'};

		#my $stringToBeSigned = $clientSecret;
		#foreach my $key (sort(keys(%sysParams))) {
		#	$stringToBeSigned .= "$key$sysParams{$key}";
		#}
		#$stringToBeSigned .= $clientSecret;
		#my $md5 = uc(md5_hex($stringToBeSigned));
		#$sysParams{"sign"} = $md5;

		#my $requestUrl = $gatewayUrl . "?";
		#foreach my $key (sort(keys(%sysParams))) {
		#	$requestUrl .= "$key=" . uri_escape($sysParams{$key}) . "&";
		#}

		#my $curl_new = WWW::Curl::Easy->new;
		#$curl_new->setopt(CURLOPT_HEADER,1);
		#$curl_new->setopt(CURLOPT_URL, $requestUrl);

		#my $response_new;
		#$curl_new->setopt(CURLOPT_WRITEDATA,\$response_new);
		#my $retcode_new = $curl_new->perform;
		#if ($retcode_new == 0) {
		#	$response_new = HTTP::Response->parse($response_new);
		#	my $xml_new = $response_new->decoded_content;
		#	my $json_new = from_json($xml_new);
		#	if(defined($json_new->{'user_seller_get_response'}->{'user'}->{'nick'}){
		#		$resData{'code'} = 0;
		#	} else {	
		#		$resData{'code'} = 1;
		#	}
		#	$resData{'session'} = $sysParams{"session"};
		#} else {
		#	$resData{'code'} = 1;
		#}
	} else {
			$resData{'code'} = 1;
	}
	return \%resData;
}
__PACKAGE__->meta->make_immutable;

1;
